package com.eascs.admin.o2o.badloan.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.back.entity.O2oBackEntity;
import com.eascs.admin.o2o.back.service.O2oBackService;
import com.eascs.admin.o2o.badloan.entity.O2oBadLoanPageVo;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.detail.entity.OaLoanDetailEntity;
import com.eascs.admin.o2o.detail.service.OaLoanapplyDetailService;
import com.eascs.admin.o2o.internal.controller.PayMentViewController;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oEaLoanDataEnity;
import com.eascs.admin.o2o.loan.entity.O2oEaLoanDataTdEnity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.OaLoanApplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.settle.entity.O2oSettleEntity;
import com.eascs.admin.o2o.settle.service.O2oSettleService;
import com.eascs.admin.o2o.settle.vo.O2oSettleVo;
import com.eascs.afterloan.controller.O2oAfterLoanController;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.impl.O2oDataListServiceImpl;
import com.eascs.loan.form.O2oLoanForm;
import com.eascs.loan.form.O2oPaymentsForm;
import com.eascs.loan.service.impl.O2oLoanServiceImpl;
import com.eascs.loan.service.impl.O2oPaymentsServiceImpl;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.service.impl.O2oPayServiceImpl;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxButton;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("/badloan")
public class O2oBadLoanController extends BaseMasterViewController {

//	@Override
//	public void preHandle() {
//		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "afterLoanManage");
//	}

	@Autowired
	O2oBadLoanService service;

	@Autowired
	private O2oPaymentsServiceImpl paymentServiceImpl;

	@Autowired
	private O2oLoanServiceImpl o2oLoanServiceImpl;

	@Autowired
	private O2oLoanapplyService loanService;

	@Autowired
	private O2oDataListServiceImpl o2oDataListService;

	@Autowired
	private OaLoanapplyDetailService oaDetailService;

	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	O2oBackService backService;

	/**
	 * @Description:
	 * 				<p>
	 *               代偿数据查询
	 *               </p>
	 * @author CXW
	 * @date 2017年5月2日 上午10:01:52
	 * @version V1.0
	 */
	@RequestMapping("/index")
	public String index(O2oBadLoanPageVo vo) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "badloan");
		vo.setPageSize(10);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		String o2ourl = "/badloan/index";
		String reporto2ourl = "/badloan/download";
		String billCode = vo.getBillCode() == null ? "" : vo.getBillCode();
		String loanType = vo.getLoanType() == null ? "" : vo.getLoanType();
		String loanerName = vo.getLoanerName() == null ? "" : vo.getLoanerName();
		String province = vo.getProvince() == null ? "" : vo.getProvince();
		String billcodeea = vo.getBillcodeea() == null ? "" : vo.getBillcodeea();
		String payDateStart = vo.getPayDateStart() == null ? "" : vo.getPayDateStart();
		String payDateEnd = vo.getPayDateEnd() == null ? "" : vo.getPayDateEnd();
		String bankType = vo.getBankType() == null ? "" : vo.getBankType();
		String hostProvince = vo.getHostProvince() == null ? "" : vo.getHostProvince();
		String flowStatus = vo.getFlowStatus() == null ? "" : vo.getFlowStatus();
		o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanType", loanType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanerName", loanerName);
		o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
		o2ourl = UrlUtil.appendUrl(o2ourl, "billcodeea", billcodeea);
		o2ourl = UrlUtil.appendUrl(o2ourl, "payDateStart", payDateStart);
		o2ourl = UrlUtil.appendUrl(o2ourl, "payDateEnd", payDateEnd);
		o2ourl = UrlUtil.appendUrl(o2ourl, "bankType", bankType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "hostProvince", hostProvince);
		o2ourl = UrlUtil.appendUrl(o2ourl, "flowStatus", flowStatus);
		o2ourl = o2ourl + "&pageIndex=";

		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billCode", billCode);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanType", loanType);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanerName", loanerName);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "province", province);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billcodeea", billcodeea);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateStart", payDateStart);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateEnd", payDateEnd);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "bankType", bankType);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "hostProvince", hostProvince);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "flowStatus", flowStatus);
		PageResult<Object[]> pageResult = service.getByPage(vo);
		String titles[] = { "贷款单号", "终端贷款单号", "省份", "借款人姓名", "经办平台", "付款类型", "代偿类型", "代偿或付款时间", "代偿总额(元)", "代偿回款总额(元)", "最后一次回款时间", "结清状态" };// ,
		Format[] formats = new Format[] { null, null, null, null, null, null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null };// ,
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("OTO_PAY_TYPE"), new SelectDataOption("BAD_LOAN_TYPE"), null, null, null, null };
		Button[] titleButtons = new Button[] { ButtonHelper.createOpenButton(null, "/badloan/detail?loanDataId=") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setFirstRenderColumnIndex(2);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setTitleButtons(titleButtons);
		o2oPagingInfo.setFormats(formats);
		ViewContext.put("paginationInfo", o2oPagingInfo);
		ViewContext.put("vo", vo);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "/badloan/index";
	}

	/**
	 * @Description:
	 * 				<p>
	 *               接力分期数据查询
	 *               </p>
	 * @author CXW
	 * @date 2017年5月2日 上午10:01:52
	 * @version V1.0
	 */
	@RequestMapping("/jlfq")
	public String indexJlFq(O2oBadLoanPageVo vo) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "JLFQData");
		vo.setPageSize(10);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		String o2ourl = "/badloan/jlfq";
		String reporto2ourl = "/badloan/jlfq_download";
		String billCode = vo.getBillCode() == null ? "" : vo.getBillCode();
		String loanType = vo.getLoanType() == null ? "" : vo.getLoanType();
		String loanerName = vo.getLoanerName() == null ? "" : vo.getLoanerName();
		String province = vo.getProvince() == null ? "" : vo.getProvince();
		String billcodeea = vo.getBillcodeea() == null ? "" : vo.getBillcodeea();
		String payDateStart = vo.getPayDateStart() == null ? "" : vo.getPayDateStart();
		String payDateEnd = vo.getPayDateEnd() == null ? "" : vo.getPayDateEnd();
		String bankType = vo.getBankType() == null ? "" : vo.getBankType();
		String hostProvince = vo.getHostProvince() == null ? "" : vo.getHostProvince();
		o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanType", loanType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanerName", loanerName);
		o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
		o2ourl = UrlUtil.appendUrl(o2ourl, "billcodeea", billcodeea);
		o2ourl = UrlUtil.appendUrl(o2ourl, "payDateStart", payDateStart);
		o2ourl = UrlUtil.appendUrl(o2ourl, "payDateEnd", payDateEnd);
		o2ourl = UrlUtil.appendUrl(o2ourl, "bankType", bankType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "hostProvince", hostProvince);
		o2ourl = o2ourl + "&pageIndex=";

		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billCode", billCode);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanType", loanType);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanerName", loanerName);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "province", province);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "billcodeea", billcodeea);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateStart", payDateStart);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "payDateEnd", payDateEnd);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "bankType", bankType);
		reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "hostProvince", hostProvince);
		PageResult<Object[]> pageResult = service.getByFqJl(vo);
		String titles[] = { "贷款单号", "终端贷款单号", "省份", "借款人姓名", "经办平台", "付款类型", "代偿类型", "代偿或付款时间", "代偿总额(元)", "代偿回款总额(元)", "最后一次回款时间", "结清状态" };// ,
		Format[] formats = new Format[] { null, null, null, null, null, null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null };// ,
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("OTO_PAY_TYPE"), new SelectDataOption("BAD_LOAN_TYPE"), null, null, null, null };
		Button[] titleButtons = new Button[] { ButtonHelper.createOpenButton(null, "/badloan/detail?loanDataId=") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setFirstRenderColumnIndex(2);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setTitleButtons(titleButtons);
		o2oPagingInfo.setFormats(formats);
		ViewContext.put("paginationInfo", o2oPagingInfo);
		ViewContext.put("vo", vo);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "/badloan/jlfq_index";
	}

	@RequestMapping("/open_find")
	public String openFindBadLoaneXplan(O2oLoanForm loanForm) {
		O2oEaLoanDataEnity dataEnity = service.findById(loanForm.getBankLoanId());
		loanForm.setPayType(dataEnity.getPayType());
		loanForm.setBillCode(dataEnity.getBillCodeEa());
		return common(loanForm, "show");
	}

	@RequestMapping("/open_edit")
	public String openEditBadLoaneXplan(O2oLoanForm loanForm) {
		O2oEaLoanDataEnity dataEnity = service.findById(loanForm.getBankLoanId());
		loanForm.setPayType(dataEnity.getPayType());
		loanForm.setBillCode(dataEnity.getBillCode());
		return common(loanForm, "edit");
	}

	@Autowired
	O2oSettleService o2oSettleService;
	@Autowired
	private O2oPayServiceImpl o2oPayServiceImpl;

	@RequestMapping("/detail")
	public String detail(O2oLoanForm loanForm) {
		O2oEaLoanDataEnity dataEnity = service.findByIdOrRecordIdDetail(loanForm);
		O2oLoanapplyEntity loanapplyEntity = loanService.findBillCode1(dataEnity.getBillCodeEa());
		String endLoanTime = "";
		if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getId())) {
			endLoanTime = service.findEndReloanTime(dataEnity.getId());
		}
		O2oPayEntity o2oPayEntity = new O2oPayEntity();
		if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getPayId())) {
			o2oPayEntity = o2oPayServiceImpl.findById(dataEnity.getPayId());
		}
		O2oSettleVo vo = new O2oSettleVo();
		vo.setEaLoadId(dataEnity.getId());
		O2oSettleEntity o2oSettleEntity = o2oSettleService.findEntity(vo);
		O2oBackEntity backEntity = backService.getEntityByLoanNo(loanapplyEntity.getLoanapplyNo());
		ViewContext.put("dataEnity", dataEnity);
		ViewContext.put("o2oPayEntity", o2oPayEntity);
		ViewContext.put("o2oSettleEntity", o2oSettleEntity);
		ViewContext.put("endLoanTime", endLoanTime);
		ViewContext.put("backEntity", backEntity);
		ViewContext.put("loanApplyNo", loanapplyEntity.getLoanapplyNo());
		return "/badloan/detail";
	}

	private String common(O2oLoanForm o2oLoanForm, String operType) {
		String returnMsg = "";
		String oldPaytype = "";
		if (StringUtils.isNotEmpty(o2oLoanForm.getBillCode())) {
			List<Object[]> bill_list = null;
			if (operType.equals("edit")) {
				if (o2oLoanForm.getBillCode().startsWith("O2O")) { // 老系统数据以O2O开头
					o2oLoanForm = getOaO2oLoanForm(o2oLoanForm);
				} else {
					bill_list = o2oLoanServiceImpl.getEaData(o2oLoanForm.getBillCode(), o2oLoanForm.getPayType());
				}
				returnMsg = "/badloan/edit_loan_explan";
			} else if (operType.equals("show")) {
				if (o2oLoanForm.getBillCode().startsWith("O2O")) { // 老系统数据以O2O开头
					o2oLoanForm = getOaO2oLoanForm(o2oLoanForm);
					oldPaytype = o2oLoanForm.getPayType();
				} else {
					bill_list = o2oLoanServiceImpl.getEaData(o2oLoanForm.getBillCode(), o2oLoanForm.getPayType());
				}
				returnMsg = "/badloan/show_loan";
			} else {
				bill_list = o2oLoanServiceImpl.isBillCodeExists(o2oLoanForm.getBillCode(), null, null);
				returnMsg = "/badloan/show_loan";
			}

			if ((bill_list != null && bill_list.size() > 0)) {
				Object[] o = bill_list.get(0);
				if (o[1] != null) {
					String loanerCard = (String) o[1];
					o2oLoanForm.setLoanerCard(loanerCard);
				}
				if (o[2] != null) {
					String loanerName = (String) o[2];
					o2oLoanForm.setLoanerName(loanerName);
				}
				if (o[3] != null) {
					String loanBank = (String) o[3];
					o2oLoanForm.setLoanBank(loanBank);
				}
				if (o[4] != null) {
					BigDecimal applyAmount = (BigDecimal) o[4];
					o2oLoanForm.setApplyAmount(applyAmount);
				}
				if (o[5] != null) {
					BigDecimal loanRate = (BigDecimal) o[5];
					o2oLoanForm.setLoanRate(loanRate);
				}

				if (o[6] != null) {
					BigDecimal loanAmount = (BigDecimal) o[6];
					o2oLoanForm.setLoanAmount(loanAmount);
				}
				if (o[7] != null) {
					int loanTerm = 0;
					if (o[7] instanceof String) {
						loanTerm = Integer.parseInt((String) o[7]);
					} else {
						loanTerm = (int) o[7];
					}
					o2oLoanForm.setLoanTerm(loanTerm);
				}
				if (o[8] != null) {
					String loanDate = "";
					if (operType.equals("edit") || operType.equals("show")) {
						if (o[8] instanceof Date) {
							Date loan = (Date) o[8];
							loanDate = DateUtils.formateStandDate(loan);
						} else {
							loanDate = (String) o[8];
						}
					} else {
						loanDate = (String) o[8];
					}
					o2oLoanForm.setLoanDate(loanDate);
				}
				if (o[9] != null) {
					if (o2oLoanForm.getBillCode().startsWith("O2O")) { // 老系统数据以O2O开头
						O2oLoanapplyEntity loan = new O2oLoanapplyEntity();
						java.sql.Date endBankDate = (java.sql.Date) o[9];
						loan.setEndBankDate(endBankDate);
						ViewContext.put("loanEntity", loan);
					} else {
						String loanBankCode = (String) o[9];
						o2oLoanForm.setLoanBankCode(loanBankCode);
					}
				}
				if (o2oLoanForm.getBillCode().startsWith("O2O")) { // 老系统数据以O2O开头
					if (o[10] != null) {
						oldPaytype = (String) o[10];
					}
				}
			}
		}
		o2oLoanForm.setLoanDate1(DateUtils.formateStandDate(getEendDate(DateUtils.formateStandDate(o2oLoanForm.getLoanDate()), o2oLoanForm.getLoanTerm())));
		ViewContext.put("voo", o2oLoanForm);

		// 银行还款计划列表
		payMents(o2oLoanForm.getBillCode(), o2oLoanForm.getType(), o2oLoanForm.getPayType());

		if (o2oLoanForm.getBillCode().startsWith("O2O")) { // 老系统数据以O2O开头
			ViewContext.put("payType", oldPaytype);
		}
		// 还款记录查询
		if (operType.equals("show"))
			hkHistory(o2oLoanForm.getBillCode());
		return returnMsg;
	}

	public Date getEendDate(Date date, int loanTerm) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(2, loanTerm);
		return gc.getTime();
	}

	@RequestMapping("/payments_list")
	public String paymentsList(O2oPaymentsForm o2oPaymentsForm) {
		o2oPaymentsForm.setPageSize(10);
		PageResult<Object[]> pageResult = service.paymentsList(o2oPaymentsForm);
		String[] titles = { "贷款单号", "借款人姓名", "借款人证件号", "还款期数", "应还款日期", "剩余本金", "应还本金", "应还利息", "本期应还款" };
		String findCondition = "";
		String pageUrl = "/badloan/payments_list";

		if (o2oPaymentsForm != null) {
			String billCode = o2oPaymentsForm.getBillCode() == null ? "" : o2oPaymentsForm.getBillCode();
			String beginPaymentsDate = o2oPaymentsForm.getBeginPaymentsDate() == null ? "" : o2oPaymentsForm.getBeginPaymentsDate();
			String endPaymentsDate = o2oPaymentsForm.getEndPaymentsDate() == null ? "" : o2oPaymentsForm.getEndPaymentsDate();
			findCondition = "?billCode=" + billCode + "&beginPaymentsDate=" + beginPaymentsDate + "&endPaymentsDate=" + endPaymentsDate;
			pageUrl = pageUrl + findCondition;
		}
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&showPage=");
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除", "/rbadloan/delPayments?payments_id=") };
		paginationInfo.setMoreButtons(dealButton);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", o2oPaymentsForm);
		BaseRestResult.refresh();
		return "/badloan/payments_list";
	}

	public void payMents(String billCode, String type, String payType) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setBillCode(billCode);
		o2oPaymentsForm.setPageSize(100);
		PageResult<Object[]> pageResult = service.paymentsList(o2oPaymentsForm);
		String[] titles = { "贷款单号", "借款人姓名", "借款人证件号", "还款期数", "应还款日期", "剩余本金", "应还本金", "应还利息" };
		String pageUrl = "/badloan/payments_list";
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&showPage=");
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除", "/rbadloan/delPayments?bill_code=" + billCode + "&payments_id=") };
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", o2oPaymentsForm);
		ViewContext.put("payType", payType);
		if (pageResult.getData().size() > 0) {
			ViewContext.put("upload", "upload");
		}

	}

	/**
	 * @Description:
	 * 				<p>
	 *               查询还款记录
	 *               </p>
	 * @author CXW
	 * @date 2016年9月8日 下午1:36:37
	 * @version V1.0
	 * @param billCode
	 * @return void
	 */
	public void hkHistory(String billCode) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setBillCode(billCode);
		o2oPaymentsForm.setPageSize(10);
		PageResult<Object[]> pageResult = paymentServiceImpl.newRepaymentsList(o2oPaymentsForm);
		String titles[] = { "发生时间", "当前应还本息", "当前应还本金", "当前应还利息", "本次回款金额", "本次回款本金", "本次回款利息", "本次实际还款时间", "还款间隔", "当前欠还余额", "还款凭证", "流程状态" };//
		Button start_upButton = ButtonHelper.createAjaxButton("发起回款流程", "/rbadloan/start?id=", "startUpBadLoan");
		AjaxButton detailButton = new AjaxButton("查看回款流程", "/rbadloan/findRecordView?id=");
		start_upButton.setShowButtonFilter(showBottun);
		detailButton.setShowButtonFilter(showBottunDetail);
		Button[] dealButton = new Button[] { start_upButton, detailButton };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles);
		Button fileButton = ButtonHelper.createOpenButton("查看", "/file/download?datalistno={11}");
		o2oPagingInfo.setTitleButtons(new Button[] { null, null, null, null, null, null, null, null, null, null, fileButton });
		o2oPagingInfo.setMoreButtons(dealButton);
		o2oPagingInfo.setBuildPagingNavigation(false);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setBuildRowNumber(true);
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, null, null, null, null, new SelectDataOption("PAY_STATUS") };
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		ViewContext.put("o2oPagingInfo", o2oPagingInfo);
	}

	/**
	 * 是否显示发起流程还款按钮
	 */
	public ShowButtonFilter showBottun = new ShowButtonFilter() {

		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[12].equals(StatusContexts.O2O_NEW)) {
				return true;
			} else {
				return false;
			}
		}
	};
	/**
	 * 是否显示查看回款流程
	 */
	public ShowButtonFilter showBottunDetail = new ShowButtonFilter() {

		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[12].equals(StatusContexts.O2O_NEW)) {
				return false;
			} else {
				return true;
			}
		}
	};

	/**
	 * @Description:
	 * 				<p>
	 *               查询实际放款时间是否等于计划放款最后时间
	 *               </p>
	 * @author CXW
	 * @date 2016年9月18日 上午9:42:50
	 * @version V1.0
	 * @param billCode
	 * @return boolean
	 */
	public boolean isExpireTime(String billCode) {
		O2oLoanapplyEntity loan = loanService.fingByBillCode(billCode);
		if (billCode.contains("O2O")) {
			loan = new O2oLoanapplyEntity();
			OaLoanDetailEntity oaLoanDetail = oaDetailService.queryBasic(billCode);
			GregorianCalendar gc = new GregorianCalendar();
			gc.setTime(oaLoanDetail.getLoaddate());
			gc.add(2, Integer.parseInt(oaLoanDetail.getLoanTerm()));
			java.sql.Date date = new java.sql.Date(gc.getTime().getTime());
			loan.setEndBankDate(date);
		}
		O2oEaLoanDataTdEnity dataTdEnity = service.findDataTdByBillCode(billCode);
		if (null == loan || null == dataTdEnity) {
			return false;
		} else {
			if (null == loan.getEndBankDate() || null == dataTdEnity.getPaymentsDate()) {
				return false;
			}
			Calendar loanDate = Calendar.getInstance();
			loanDate.setTime(loan.getEndBankDate());
			Calendar paymentDate = Calendar.getInstance();
			paymentDate.setTime(dataTdEnity.getPaymentsDate());
			boolean isSameYear = loanDate.get(Calendar.YEAR) == paymentDate.get(Calendar.YEAR);
			boolean isSameMonth = isSameYear && loanDate.get(Calendar.MONTH) == paymentDate.get(Calendar.MONTH);
			boolean isSameDate = isSameMonth && loanDate.get(Calendar.DAY_OF_MONTH) == paymentDate.get(Calendar.DAY_OF_MONTH);
			return isSameDate;
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               查询老系统数据
	 *               </p>
	 * @author CXW
	 * @date 2016年12月9日 下午4:35:13
	 * @version V1.0
	 */
	public O2oLoanForm getOaO2oLoanForm(O2oLoanForm o2oLoanForm) {
		OaLoanDetailEntity oaLoanDetail = oaDetailService.queryBasic(o2oLoanForm.getBillCode());
		O2oEaLoanDataEnity dataEnity = service.findById(o2oLoanForm.getBankLoanId());
		o2oLoanForm.setLoanerCard(dataEnity.getLoanerCard());
		o2oLoanForm.setLoanerName(dataEnity.getLoanerName());
		o2oLoanForm.setLoanBank(dataEnity.getLoanBank());
		o2oLoanForm.setApplyAmount(dataEnity.getApplyAmount());
		o2oLoanForm.setLoanRate(new BigDecimal(oaLoanDetail.getLoanrate()));
		o2oLoanForm.setLoanAmount(dataEnity.getLoanAmount());
		o2oLoanForm.setLoanTerm(dataEnity.getLoanTerm());
		o2oLoanForm.setLoanDate(DateUtils.formateStandDate(oaLoanDetail.getLoaddate()));
		o2oLoanForm.setLoanBankCode(dataEnity.getLoanBank());
		return o2oLoanForm;
	}

	/**
	 * @Description
	 * 				<p>
	 *              </p>
	 * @author CXW
	 * @date 2016年8月26日 下午5:48:18
	 * @version V1.0
	 * @param
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/repaymentFileDiv")
	public String repaymentFileDiv(String billCode, String paymentsId) {
		O2oLoanapplyEntity loanEntity = new O2oLoanapplyEntity();
		if (billCode.contains("O2O")) {
			OaLoanApplyEntity oaLoanApplyEntity = loanService.findOaLoanByCode(billCode);
			loanEntity.setLoanapplyNo(oaLoanApplyEntity.getLoanapplyNo());
			loanEntity.setBankType(oaLoanApplyEntity.getLoanType());
			loanEntity.setEaMount(oaLoanApplyEntity.getBankLoanAmount());
			loanEntity.setLoanTerm(oaLoanApplyEntity.getLoanTerm());
			loanEntity.setPaymentTime(oaLoanApplyEntity.getLoadDate());
			loanEntity.setLtd(oaLoanApplyEntity.getLtd());
			loanEntity.setLtdCode(oaLoanApplyEntity.getLtdCode());
			loanEntity.setLtdName(oaLoanApplyEntity.getLtdName());
		} else {
			loanEntity = loanService.fingByBillCode(billCode);
		}
		if (loanEntity != null) {
			ViewContext.put("loanapplyNo", loanEntity.getLoanapplyNo());
			List<O2oDataListEntity> o2oDataList = o2oDataListService.getByBillCodeDataList(loanEntity.getLoanapplyNo(), paymentsId);
			ViewContext.put("o2oDataList", o2oDataList);
		}
		ViewContext.put("paymentsId", paymentsId);
		return "bank/repaymentFileDiv";
	}

	/**
	 * @Description:
	 * 				<p>
	 * 
	 *               </p>
	 * @author CXW
	 * @date 2017年1月4日 下午1:48:54
	 * @version V1.0
	 */
	@RequestMapping("/alllist")
	public String allList(O2oBadLoanPageVo vo) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "badLoanRecord");
		String findurl = "/rbadloan/all_list";
		String exporturl = "/badloan/export";
		if (!StringUtils.isEmpty(vo.getLoanDataId())) {
			O2oEaLoanDataEnity dataEnity = service.findById(vo.getLoanDataId());
			vo.setBillCode(dataEnity.getBillCodeEa());
		}
		String billCode = vo.getBillCode() == null ? "" : vo.getBillCode();
		String loanType = vo.getLoanType() == null ? "" : vo.getLoanType();
		String loanerName = vo.getLoanerName() == null ? "" : vo.getLoanerName();
		String province = vo.getProvince() == null ? "" : vo.getProvince();
		String loanDataId = vo.getLoanDataId() == null ? "" : vo.getLoanDataId();
		String firstTime = vo.getFirstTime() == null ? "" : vo.getFirstTime();
		String endTime = vo.getEndTime() == null ? "" : vo.getEndTime();
		String status = vo.getStatus()== null ? "" : vo.getStatus();
		String liquiName = vo.getLiquiName() == null ? "" : vo.getLiquiName();
		findurl = UrlUtil.appendUrl(findurl, "billCode", billCode);
		findurl = UrlUtil.appendUrl(findurl, "loanType", loanType);
		findurl = UrlUtil.appendUrl(findurl, "loanerName", loanerName);
		findurl = UrlUtil.appendUrl(findurl, "province", province);
		findurl = UrlUtil.appendUrl(findurl, "loanDataId", loanDataId);
		findurl = UrlUtil.appendUrl(findurl, "firstTime", firstTime);
		findurl = UrlUtil.appendUrl(findurl, "endTime", endTime);
		findurl = UrlUtil.appendUrl(findurl, "status", status);
		findurl = UrlUtil.appendUrl(findurl, "liquiName", liquiName);
		exporturl = UrlUtil.appendUrl(exporturl, "billCode", billCode);
		exporturl = UrlUtil.appendUrl(exporturl, "loanType", loanType);
		exporturl = UrlUtil.appendUrl(exporturl, "loanerName", loanerName);
		exporturl = UrlUtil.appendUrl(exporturl, "province", province);
		exporturl = UrlUtil.appendUrl(exporturl, "loanDataId", loanDataId);
		exporturl = UrlUtil.appendUrl(exporturl, "firstTime", firstTime);
		exporturl = UrlUtil.appendUrl(exporturl, "endTime", endTime);
		exporturl = UrlUtil.appendUrl(exporturl, "status", status);
		exporturl = UrlUtil.appendUrl(exporturl, "liquiName", liquiName);
		ViewContext.put("findurl", findurl);
		ViewContext.put("exporturl", exporturl);
		ViewContext.put("vo", vo);
		return "badloan/all_list";
	}

	@RequestMapping("/export")
	public void dowloand(O2oBadLoanPageVo vo, HttpServletResponse response, HttpServletRequest request) {
		vo.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = service.findByPageExport(vo);
		String path = O2oAfterLoanController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/badloan-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "不良还款记录.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			response.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(response.getOutputStream(), O2oAfterLoanController.class.getResourceAsStream("/excelTemplate/badloan-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	@RequestMapping("/download")
	public void dowanload(O2oBadLoanPageVo vo, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		vo.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = service.getByPageExport(vo);
		String path = PayMentViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/badloan.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "代偿数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oBadLoanController.class.getResourceAsStream("/excelTemplate/badloan.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	@RequestMapping("/jlfq_download")
	public void jlfq_download(O2oBadLoanPageVo vo, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		vo.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = service.getByFqJlPageExport(vo);
		String path = PayMentViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/jlfq_loan.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "接力贷分期贷数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oBadLoanController.class.getResourceAsStream("/excelTemplate/jlfq_loan.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
}
